/**
 * @file module_audio_postprocess.cc
 * @author your name (you@domain.com)
 * @brief 1号线程的一部分，根据3号线程的信号量通知，进行语音播放
 * @version 0.1
 * @date 2023-2-24
 * 
 * @copyright Copyright (c) 2022
 * 
 */
#include "module_audio_postprocess.h"
#include <semaphore.h>
#include <assert.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
extern "C"{
  #include "rkmedia_api.h"
}

static bool quit = false;
static void sigterm_handler(int sig) {
  fprintf(stderr, "signal %d\n", sig);
  quit = true;
}

sem_t bin_sem_audio; 
RK_CHAR *pInputPath = NULL;

void *module_audio_postprocess(void *arg){
  int ret = 0;
  RK_U32 u32SampleRate = 16000;
  RK_U32 u32ChnCnt = 2;
  RK_U32 u32FrameCnt = 1024;
  RK_S32 s32Volume = 100;
  // default:CARD=rockchiprk809co
  RK_CHAR *pDeviceName = "sysdefault:CARD=rockchiprk809co";
  
  SAMPLE_FORMAT_E enSampleFmt = RK_SAMPLE_FMT_S16;
  
  AO_CHN_ATTR_S ao_attr;
  ao_attr.pcAudioNode = pDeviceName;
  ao_attr.enSampleFormat = enSampleFmt;
  ao_attr.u32NbSamples = u32FrameCnt;
  ao_attr.u32SampleRate = u32SampleRate;
  ao_attr.u32Channels = u32ChnCnt;
  ret = RK_MPI_AO_SetChnAttr(0, &ao_attr);
  ret |= RK_MPI_AO_EnableChn(0);

  printf("%s initial finish\n", __func__);
  signal(SIGINT, sigterm_handler);
  MEDIA_BUFFER mb = NULL;
  RK_U32 u32Timeval = u32FrameCnt * 1000000 / u32SampleRate; // us
  RK_U32 u32ReadSize;
  MB_AUDIO_INFO_S stSampleInfo = {ao_attr.u32Channels, ao_attr.u32SampleRate,         //Todo:这个数据结构和下面的函数api找不到
                                  ao_attr.u32NbSamples, ao_attr.enSampleFormat};
  while(1){
      sem_wait(&bin_sem_audio);
      FILE *file = fopen(pInputPath, "r");

      //执行播放语音操作
      while (!quit) {
      mb = RK_MPI_MB_CreateAudioBufferExt(&stSampleInfo, RK_FALSE, 0);
      if (!mb) {
        printf("ERROR: create audio buffer\n");
        break;
      }
      u32ReadSize = RK_MPI_MB_GetSize(mb);
      printf("# TimeVal:%dus, ReadSize:%d\n", u32Timeval, u32ReadSize);
      ret = fread(RK_MPI_MB_GetPtr(mb), 1, u32ReadSize, file);
      if (!ret) {
        printf("# Get end of file!\n");
        break;
      }

      ret = RK_MPI_SYS_SendMediaBuffer(RK_ID_AO, 0, mb);      //这里我理解的mb不像是摄像头取流直接从通道的mb，而是从file中取信息放到mb中，再将mb推出去
      if (ret) {
        printf("ERROR: RK_MPI_SYS_SendMediaBuffer failed! ret = %d\n", ret);
        break;
      }
      usleep(u32Timeval);
      RK_MPI_MB_ReleaseBuffer(mb);
      mb = NULL;
  }
    if (mb)
      RK_MPI_MB_ReleaseBuffer(mb);
  }
  
}
